import { pageListCustomerAndCost,getCustomerById,updateCustomerStatus,resetCustomerPwdById } from '@/services/customer/custom_api';
import { PlusOutlined } from '@ant-design/icons';
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import {
  PageContainer,
  ProTable,
  TableDropdown
} from '@ant-design/pro-components';
import { FormattedMessage, useIntl } from '@umijs/max';
import { Button, Drawer, Input, message,Modal, Popconfirm } from 'antd';
import React, { useRef, useState, useEffect } from 'react';
import AddForm from './components/AddForm';
import {CustomerDataVo} from "../constants"


/**
 * @en-US Add node
 * @zh-CN 添加节点
 * @param fields
 */
const handleAdd = async (fields: CustomerDataVo) => {
  const hide = message.loading('正在添加');
  try {
    // await addRule({ ...fields });
    hide();
    message.success('Added successfully');
    return true;
  } catch (error) {
    hide();
    message.error('Adding failed, please try again!');
    return false;
  }
};



/**
 *  Delete node
 * @zh-CN 删除节点
 *
 * @param selectedRows
 */
const handleRemove = async (selectedRows: CustomerDataVo[]) => {
  const hide = message.loading('正在删除');
  if (!selectedRows) return true;
  try {
    // await removeRule({
    //   key: selectedRows.map((row) => row.key),
    // });
    hide();
    message.success('Deleted successfully and will refresh soon');
    return true;
  } catch (error) {
    hide();
    message.error('Delete failed, please try again');
    return false;
  }
};


const TableList: React.FC = () => {
  /**
   * @en-US Pop-up window of new window
   * @zh-CN 新建窗口的弹窗
   *  */
  const [createModalOpen, handleModalOpen] = useState<boolean>(false);
  /**
   * @en-US The pop-up window of the distribution update window
   * @zh-CN 分布更新窗口的弹窗
   * */
  const [loading, setLoading] = useState(false);
  const [updateModalOpen, handleUpdateModalOpen] = useState<boolean>(false);

  const [showDetail, setShowDetail] = useState<boolean>(false);

  const actionRef = useRef<ActionType>();
  const [currentRow, setCurrentRow] = useState<CustomerDataVo>();
  const [selectedRowsState, setSelectedRows] = useState<CustomerDataVo[]>([]);
  const [editRow, setEditRow] = useState<CustomerDataVo>();
  
 
  const getCustomerInfo = async (id: string) => {
    try {
      const response = await getCustomerById(id);
      if (response.code != 0) {
        if (!response.msg) {
          throw new Error(intl.formatMessage({ id: "request.error.create" }));
        } else {
           message.error(response.msg);
           return false;
        }
      }
      setEditRow(response.data);
    } catch (error) {
      message.error(intl.formatMessage({ id: "request.error.retry" }));
      return false;
    }
  };
  

  const queryPageData = async (pageParams: any) => {
    setLoading(true);
    try {
      const response = await pageListCustomerAndCost(pageParams);
      if (response.code != 0) {
        if (!response.msg) {
          throw new Error(intl.formatMessage({ id: "request.error.create" }));
        } else {
          message.error(response.msg);
        }
      }
      return response.data;
    } catch (error) {
      console.error(error);
      // message.error(intl.formatMessage({ id: "request.error.retry" }));
      message.error(error);      
       return false;
    }finally{
      setLoading(false);
    }
  };


  const pageQueryCustomer = async (params, sorter, filter) => {
    // 表单搜索项会从 params 传入，传递给后端接口。
    // console.log(params, sorter, filter);
    const { current, pageSize, customerCode,customerName,customerStatus } = params
    let queryParams = {};
    if (current !== undefined) queryParams.current = current;
    if (pageSize !== undefined) queryParams.pageSize = pageSize;
    if (customerCode !== undefined) queryParams.likeCode = customerCode;    
    if (customerName !== undefined) queryParams.likeName = customerName;
    if (customerStatus !== undefined) queryParams.status = Number(customerStatus);
    return await queryPageData(queryParams);
  }

  const makeActive = (record: CustomerDataVo) => {
    Modal.confirm({
      title: intl.formatMessage({ id: 'pages.customer.operation.confirm.title' }),
      content: intl.formatMessage(
        { id: 'pages.customer.status.change.confirm.content' },
        { action: intl.formatMessage({ id: record.customerStatus === 1 ? 'pages.customer.status.enable' : 'pages.customer.status.disable' }) }
      ),
      okText: intl.formatMessage({ id: 'pages.button.confirm' }),
      cancelText: intl.formatMessage({ id: 'pages.button.cancel' }),
      onOk: async () => {
        const hide = message.loading(intl.formatMessage({ id: 'pages.common.processing' }));
        try {
          const status = record.customerStatus === 1 ? 0 : 1;
          await updateCustomerStatus(record.id, status);
          hide();
          message.success(intl.formatMessage(
            { id: 'pages.customer.status.change.success' },
            { action: intl.formatMessage({ id: status === 0 ? 'pages.customer.status.enabled' : 'pages.customer.status.disabled' }) }
          ));
          if (actionRef.current) {
            actionRef.current.reload();
          }
        } catch (error) {
          hide();
          message.error(intl.formatMessage({ id: 'request.error.retry' }));
        }
      },
    });
  }

  const resetCustomerPassword = (record: CustomerDataVo) => {
    Modal.confirm({
      title: intl.formatMessage({ id: 'pages.customer.operation.confirm.title' }),
      content: intl.formatMessage(
        { id: 'pages.customer.password.reset.confirm.content' },
        { action: intl.formatMessage({ id: record.customerStatus === 1 ? 'pages.customer.status.enable' : 'pages.customer.status.disable' }) }
      ),
      okText: intl.formatMessage({ id: 'pages.button.confirm' }),
      cancelText: intl.formatMessage({ id: 'pages.button.cancel' }),
      onOk: async () => {
        const hide = message.loading(intl.formatMessage({ id: 'pages.common.processing' }));
        try {
          const status = record.customerStatus === 1 ? 0 : 1;
          await resetCustomerPwdById(record.id);
          hide();
          message.success(intl.formatMessage(
            { id: 'pages.customer.password.reset.success' },
            { action: intl.formatMessage({ id: status === 0 ? 'pages.customer.status.enabled' : 'pages.customer.status.disabled' }) }
          ));
          if (actionRef.current) {
            actionRef.current.reload();
          }
        } catch (error) {
          hide();
          message.error(intl.formatMessage({ id: 'request.error.retry' }));
        }
      },
    });
  }

  const resetCustPassword = async(record:CustomerDataVo) => {
      const hide = message.loading('Processing...');
      try {
        const status = record.customerStatus === 1 ? 0 : 1;
        await resetCustomerPwdById(record.id);
        hide();
        message.success(intl.formatMessage({ id: 'request.success.operating' }));
        if (actionRef.current) {
          actionRef.current.reload();
        }
      } catch (error) {
        hide();
        message.error(intl.formatMessage({ id: 'request.error.retry' }));
      }
  }

  /**
   * @en-US International configuration
   * @zh-CN 国际化配置
   * */
  const intl = useIntl();

  const columns: ProColumns<CustomerDataVo>[] = [
    // {
    //   title: (
    //     <FormattedMessage
    //       id="pages.searchTable.serialNumber"
    //       defaultMessage="Number"
    //     />
    //   ),
    //   dataIndex: 'index',
    //   valueType: 'indexBorder',
    //   width: 48,
    // },
    {
      title: (
        <FormattedMessage
          id="pages.searchTable.customer.code"
          defaultMessage="Code"
        />
      ),
      dataIndex: "customerCode",
      key: "customerCode",
      disable: true,
    },
    {
      title: (
        <FormattedMessage
          id="pages.searchTable.customer.name"
          defaultMessage="Name"
        />
      ),
      dataIndex: "customerName",
      key: "customerName",
      hideInForm: true,
    },
    {
      title: (
        <FormattedMessage
          id="pages.searchTable.customer.balance"
          defaultMessage="Balance"
        />
      ),
      dataIndex: "customerBalance",
      key: "customerBalance",
      sorter: true,
      search: false,
      hideInForm: true,
    },
    {
      title: (
        <FormattedMessage
          id="pages.searchTable.customer.currency"
          defaultMessage="Currency"
        />
      ),
      dataIndex: "customerCurrency",
      key: "customerCurrency",
      search: false,
      valueType: "text",
      hideInForm: true,
    },
    {
      title: (
        <FormattedMessage
          id="pages.searchTable.customer.rechargeTotal"
          defaultMessage="RechargeTotal"
        />
      ),
      dataIndex: "customerRechargeTotal",
      key: "customerRechargeTotal",
      search: false,
      sorter: true,
      hideInForm: true,
    },
    {
      title: (
        <FormattedMessage
          id="pages.searchTable.customer.status"
          defaultMessage="Status"
        />
      ),
      width: 100,
      dataIndex: "customerStatus",
      key: "customerStatus",
      hideInForm: true,
      filters: true,
      onFilter: true,
      ellipsis: true,
      valueType: "select",
      valueEnum: {
        "0": {
          text: intl.formatMessage({
            id: "pages.addForm.customer.customerStatus.0",
            defaultMessage: "Enable",
          }),   
          status: "success",   
        },
        "1": {
          text: intl.formatMessage({
            id: "pages.addForm.customer.customerStatus.1",
            defaultMessage: "Deactivate",
          }), 
          status: "error",  
        },
      },
    },
    {
      title: (
        <FormattedMessage id="pages.operating" defaultMessage="Operating" />
      ),
      dataIndex: "option",
      valueType: "option",
      fixed: "right",
      width: 120,
      disable: true,
      render: (_, record) => [
        <a
          key="edit"
          onClick={async () => {
            await getCustomerInfo(record.id);
            // console.log("current:"+JSON.stringify(record));
            setCurrentRow(record);
            handleUpdateModalOpen(true); // 打开编辑弹窗
          }}
        >
          <FormattedMessage id="pages.edit" defaultMessage="Edit" />
        </a>,
        <a
          key="config"
          onClick={() => {
            makeActive(record);
            setCurrentRow(record);
          }}
        >
          {record.customerStatus == 0 ? (
            <FormattedMessage
              id="pages.addForm.customer.customerStatus.1"
              defaultMessage="Enable"
            />
          ) : (
            <FormattedMessage
              id="pages.addForm.customer.customerStatus.0"
              defaultMessage="Deactivate"
            />
          )}
        </a>,

        <TableDropdown
          key="actionGroup"
          onSelect={(key) => {
            if (key === "resetPassword") {
              // 手动触发重置密码逻辑
              resetCustomerPassword(record);
            } else if (key === "reload") {
              actionRef.current?.reload();
            }
            // 可以根据需要扩展其他菜单项的逻辑
          }}
          menus={[
            // { key: 'copy', name: '复制' },
            // { key: 'delete', name: '删除' },
            {
              key: "resetPassword",
              name: (
                <FormattedMessage
                  id="password.update.reset"
                  defaultMessage="Reset Password"
                />
              ),
            }, // 新增重置密码菜单项
          ]}
        />,
      ],
    },
  ];

  return (
    <PageContainer title={false}>
      <ProTable<CustomerDataVo, API.PageParams>
        headerTitle={intl.formatMessage({
          id: 'pages.searchTable.customer.list',
          defaultMessage: 'Enquiry Form',
        })}
        actionRef={actionRef}
        loading={loading}
        rowKey="key"
        search={{
          labelWidth: 120,
        }}
        toolBarRender={() => [
          <Button
            type="primary"
            key="primary"
            onClick={() => {
              //新建
              handleModalOpen(true);
            }}
          >
            <PlusOutlined /> {" "}
            <FormattedMessage id="pages.searchTable.customer.create" defaultMessage="New" />
          </Button>,
        ]}
        request={pageQueryCustomer}
        columns={columns}
        // rowSelection={{
        //   onChange: (_, selectedRows) => {
        //     setSelectedRows(selectedRows);
        //   },
        // }}
      />
      

      <AddForm
        // width="40%"
        visible={createModalOpen}
        // onOpenChange={handleModalOpen}
        onCancel={async () => { handleModalOpen(false) }}
        onSuccess={function (): void {
          handleModalOpen(false)
          setCurrentRow(undefined);
          if (actionRef.current) {
            actionRef.current.reload();
          }
        }}
      >
      </AddForm>

      <AddForm
        visible={updateModalOpen}
        values={editRow}
        onCancel={async () => {  
          handleUpdateModalOpen(false);
          setCurrentRow(undefined);
          setEditRow(undefined);
         }}
        onSuccess={function (): void {
          handleUpdateModalOpen(false)
          setCurrentRow(undefined);
          setEditRow(undefined);
          if (actionRef.current) {
            actionRef.current.reload();
          }
        }}
      >
      </AddForm>
    </PageContainer>
  );
};

export default TableList;
